package com.example.demo.LeetCode.list;


public class MergeTwoList {
    public static void main(String[] args) {
        ListNode listNode = mergeTwoList();
        ListNode p = listNode;
        while (p != null){
            System.out.println(p.val);
            p = p.next;
        }
    }

    private static ListNode mergeTwoList(){
        ListNode head1 = createListNode1();
        ListNode head2 = createListNode2();
        //虚拟头结点
        ListNode dummy = new ListNode(-1),p = dummy;
        ListNode p1 = head1,p2 = head2;
        while (p1 != null && p2 != null){
            //比较p1和p2两个指针
            //将值较小的节点接到p指针
            if(p1.val > p2.val){
                p.next = p2;
                p2 = p2.next;
            }else{
                p.next = p1;
                p1 = p1.next;
            }
            //p指针不断前进
            p = p.next;
        }

        if(p1 != null){
            p.next = p1;
        }
        if(p2 != null){
            p.next = p2;
        }
        return dummy.next;
    }

    private static  ListNode createListNode1(){
        ListNode head1 = new ListNode(1);
        ListNode next1 = new ListNode(2);
        ListNode next12 = new ListNode(3);
        head1.next = next1;
        next1.next = next12;
        return head1;
    }

    private static  ListNode createListNode2(){
        ListNode head1 = new ListNode(1);
        ListNode next1 = new ListNode(2);
        ListNode next12 = new ListNode(3);
        ListNode next3 = new ListNode(4);
        head1.next = next1;
        next1.next = next12;
        next12.next = next3;
        return head1;
    }
}


